<template>
  <div v-show="!isMain && !isView" class="add-equip-detail">
    <px-scrollbar class="add-equip-content">
      <px-button style="margin-top: 16px; margin-bottom: -4px" type="primary" icon="ArrowLeft" @click="backMainPage">返回</px-button>
      <EditDropDown dropdownTitle="盘点基本信息">
        <template v-slot:content>
          <px-form ref="formRef" :inline="true" :model="formValue" :rules="rules" label-position="right" label-width="120px">
            <px-row>
              <px-col :span="8">
                <px-form-item label="盘点名称" prop="takeStockName">
                  <px-input v-model="formValue.takeStockName" placeholder="请输入盘点名称" maxlength="50" clearable />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="盘点编码" prop="takeStockCode">
                  <px-input v-model="formValue.takeStockCode" placeholder="请输入盘点编码" maxlength="50" disabled />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <EquipClassSelect :isRequired="true" :className="formValue.className" @changeClassName="changeClassName" />
              </px-col>
              <px-col :span="8">
                <px-form-item label="仓库" prop="warehousePosition">
                  <px-select v-model="formValue.warehousePosition" placeholder="请选择仓库" filterable clearable>
                    <px-option v-for="item in warehousePositionList" :key="item.id" :label="item.name" :value="item.value" />
                  </px-select>
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="盘点负责人" prop="takeStockPeople">
                  <px-select-v2
                    v-model="formValue.takeStockPeople"
                    filterable
                    clearable
                    :options="takeStockPeopleList"
                    placeholder="请选择盘点负责人"
                    @change="principalChange"
                  />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="计划日期" prop="planDate">
                  <px-date-picker
                    v-model="formValue.planDate"
                    type="daterange"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    unlink-panels
                    :disabled-date="disabledDate"
                    @change="changePlanDate"
                  />
                </px-form-item>
              </px-col>
              <px-col :span="24">
                <px-form-item label="备注" prop="remark">
                  <px-input
                    v-model="formValue.remark"
                    type="textarea"
                    :autosize="{ minRows: 2, maxRows: 4 }"
                    placeholder="请输入备注"
                    maxlength="1000"
                  />
                </px-form-item>
              </px-col>
            </px-row>
          </px-form>
        </template>
      </EditDropDown>
      <EditDropDown dropdownTitle="备件盘点表">
        <template v-slot:content>
          <div style="display: flex; align-items: center; margin-top: -12px; margin-bottom: 12px">
            <div style="font-size: 14px">盘点范围</div>
            <px-select
              v-model="formValue.takeStockScope"
              placeholder="请选择盘点范围"
              style="margin-right: 16px; margin-left: 24px"
              @change="changeTakeStockScope"
              filterable
              clearable
            >
              <px-option v-for="item in takeStockScopeList" :key="item.id" :label="item.name" :value="item.value" />
            </px-select>
            <px-button v-if="formValue.takeStockScope === 'choose'" type="primary" @click="dialogVisible = true">选择备件</px-button>
          </div>
          <px-table :data="formValue.tableData" class="equip-table" size="small" height="350" border>
            <px-table-column type="index" label="序号" width="80" align="center" fixed="left" />
            <px-table-column
              v-for="(item, index) in tableColumns"
              :key="index"
              :label="item.label"
              :min-width="item.minWidth"
              :show-overflow-tooltip="item.showOverflowTooltip"
            >
              <template #default="scope">{{
                scope.row[item.prop] === 0 ? scope.row[item.prop] : scope.row[item.prop] ? scope.row[item.prop] : "-"
              }}</template>
            </px-table-column>
            <px-table-column label="操作" width="60" fixed="right" align="center" v-if="formValue.takeStockScope !== 'all'">
              <template #default="scope">
                <px-tooltip content="移除" placement="top">
                  <px-button link icon="Delete" type="danger" @click="handleEqpDelete(scope.$index)" />
                </px-tooltip>
              </template>
            </px-table-column>
          </px-table>
          <pagination
            v-if="total > 0 && formValue.takeStockScope === 'all'"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            class="equip-table-pagination"
            :total="total"
            @pagination="queryTable"
          />
        </template>
      </EditDropDown>
    </px-scrollbar>
    <div class="info-form-btns">
      <px-button @click="backMainPage">取消</px-button>
      <px-button v-if="props.isDraftVisible" type="primary" @click="handleSubmit(formRef, true)">保存为草稿</px-button>
      <px-button type="primary" @click="handleSubmit(formRef, false)">保存</px-button>
    </div>
  </div>
  <!-- 选择备件弹窗 -->
  <AddSparePartsDialog :visible="dialogVisible" :className="formValue.className" @closeDialog="closeDialog" @addTableRow="addTableRow" />
</template>
<script setup lang="ts">
import { queryDictData } from "@/api/common";
import EditDropDown from "@/views/all/equip/components/EditDropDown.vue";
import EquipClassSelect from "@/views/all/equip/components/EquipClassSelect.vue";
import {
  addSparePartsTakeStock,
  editSparePartsTakeStock,
  getSparePartsTakeStock,
  getTakeStockCode,
  querySparePartsWarehousingInfo
} from "@/api/equip/spareParts";
import { getEmployeeIdAndName } from "@/utils/pengxi";
import { PxMessage } from "px-ui";
import { computed, reactive, ref, toRefs, watch } from "vue";
import AddSparePartsDialog from "./AddSparePartsDialog.vue";

// 调用父级-返回主页、查询列表方法
const emits = defineEmits(["backMainPage", "queryTable"]);
// 父级传过来的值
const props = defineProps(["isMain", "isView", "isDraftVisible", "drawerType", "sparePartsId"]);
// 显示隐藏
const isMain = computed(() => props.isMain);
const isView = computed(() => props.isView);
// 页面本身的值
const formRef = ref();
const state = reactive<any>({
  formValue: {
    id: "",
    takeStockName: "",
    takeStockCode: "",
    className: "",
    warehousePosition: "",
    planDate: "",
    planStartDate: "",
    planEndDate: "",
    takeStockPeople: null,
    takeStockPeopleName: "",
    remark: "",
    takeStockScope: "all",
    tableData: [],
    isDraft: false
  },
  warehousePositionList: [], // 仓库下拉框
  takeStockPeopleList: [], // 责任人下拉框
  takeStockScopeList: [
    { name: "全面盘点", value: "all" },
    { name: "指定盘点", value: "choose" }
  ],
  total: 0,
  dialogVisible: false,
  tableColumns: [
    { prop: "categoryDesc", label: "种类", minWidth: "140", showOverflowTooltip: true, fixed: "left" },
    { prop: "sparePartName", label: "名称", minWidth: "140", showOverflowTooltip: true },
    { prop: "sparePartCode", label: "编码", minWidth: "140", showOverflowTooltip: true },
    { prop: "classNameDesc", label: "科室", minWidth: "100", showOverflowTooltip: true },
    { prop: "typeName", label: "类型", minWidth: "100", showOverflowTooltip: true },
    { prop: "brandName", label: "品牌", minWidth: "100", showOverflowTooltip: true },
    { prop: "supplyModel", label: "厂商型号", minWidth: "100", showOverflowTooltip: true },
    { prop: "model", label: "厂内型号", minWidth: "100", showOverflowTooltip: true },
    { prop: "currentStock", label: "库存量", minWidth: "100", showOverflowTooltip: true },
    { prop: "alarmStock", label: "安全库存量", minWidth: "100", showOverflowTooltip: true },
    { prop: "warehousePositionDesc", label: "库位", minWidth: "100", showOverflowTooltip: true }
  ],
  queryParams: {
    pageNum: 1,
    pageSize: 10
  }
});
const { formValue, warehousePositionList, takeStockPeopleList, takeStockScopeList, total, dialogVisible, tableColumns, queryParams } = toRefs(state);
// 表单校验规则
const rules = computed(() => ({
  takeStockName: [{ required: true, message: "盘点名称不能为空", trigger: "blur" }],
  takeStockCode: [{ required: true, message: "盘点编码不能为空", trigger: "blur" }],
  planDate: [{ required: true, message: "计划日期不能为空", trigger: "blur" }]
}));
// 树形选择图
const defaultProps = {
  children: "children",
  label: "name"
};
// 禁用日期
const disabledDate = (time: Date) => {
  return time.getTime() < new Date().getTime() - 8.64e7;
};
// 监视isMain和isView值
watch(isMain, async val => {
  if (!val && !props.isView) {
    formRef.value.resetFields();
    queryWarehousePositionSelect();
    takeStockPeopleList.value = await getEmployeeIdAndName();
    if (props.drawerType === "add") {
      changeTakeStockScope();
      const data = await getTakeStockCode({});
      formValue.value.takeStockCode = data;
      formValue.value.takeStockName = "";
      formValue.value.className = "";
      formValue.value.warehousePosition = "";
      formValue.value.planDate = "";
      formValue.value.planStartDate = "";
      formValue.value.planEndDate = "";
      formValue.value.takeStockPeople = null;
      formValue.value.takeStockPeopleName = "";
      formValue.value.remark = "";
      formValue.value.takeStockScope = "all";
      formValue.value.isDraft = false;
      delete formValue.value.id;
    } else if (props.drawerType === "edit") {
      getDetail();
    }
  } else {
    formValue.value = {
      id: "",
      takeStockName: "",
      takeStockCode: "",
      className: "",
      warehousePosition: "",
      planDate: "",
      planStartDate: "",
      planEndDate: "",
      takeStockPeople: null,
      takeStockPeopleName: "",
      remark: "",
      takeStockScope: "all",
      tableData: [],
      isDraft: false
    };
  }
});
// 仓库
const queryWarehousePositionSelect = async () => {
  warehousePositionList.value = [];
  const params = {
    typeCode: "warehouse"
  };
  const data = await queryDictData(params);
  warehousePositionList.value = data;
};
// 获取takeStockPeopleName
const principalChange = val => {
  const arr = takeStockPeopleList.value.filter(item => {
    return item.value === val;
  });
  if (arr && arr.length > 0) {
    formValue.value.takeStockPeopleName = arr[0].label;
    formValue.value.principalPhone = arr[0].phone;
  }
};
// 获取计划日期开始及结束
const changePlanDate = val => {
  formValue.value.planStartDate = val[0];
  formValue.value.planEndDate = val[1];
};
// 获取范围
const changeTakeStockScope = async () => {
  if (formValue.value.takeStockScope === "all") {
    queryParams.value.pageNum = 1;
    queryParams.value.pageSize = 10;
    queryTable();
  } else if (formValue.value.takeStockScope === "choose") {
    formValue.value.tableData = [];
  }
};
// 查询表格数据
const queryTable = async () => {
  const params = {
    className: formValue.value.className,
    pageNum: queryParams.value.pageNum,
    pageSize: queryParams.value.pageSize
  };
  const data = await querySparePartsWarehousingInfo(params);
  formValue.value.tableData = data?.data;
  total.value = data?.total;
};
// 获取详情接口
const getDetail = async () => {
  const params = {
    id: props.sparePartsId
  };
  const data = await getSparePartsTakeStock(params);
  formValue.value.id = data.id;
  formValue.value.takeStockName = data.takeStockName;
  formValue.value.takeStockCode = data.takeStockCode;
  formValue.value.className = data.className;
  formValue.value.warehousePosition = data.warehousePosition;
  formValue.value.planDate = [data.planStartDate, data.planEndDate];
  formValue.value.planStartDate = data.planStartDate;
  formValue.value.planEndDate = data.planEndDate;
  formValue.value.takeStockPeople = data.takeStockPeople;
  formValue.value.takeStockPeopleName = data.takeStockPeopleName;
  formValue.value.remark = data.remark;
  formValue.value.takeStockScope = data.takeStockScope;
  formValue.value.tableData = data.inventoryDetailDTOList;
  formValue.value.isDraft = data.isDraft;
};
// 返回主页面
const backMainPage = () => {
  formRef.value.resetFields();
  emits("backMainPage");
};
// 关闭子级dialog弹窗
const closeDialog = () => {
  dialogVisible.value = false;
};
// 选择备件后添加表格数据
const addTableRow = val => {
  if (val && val.length > 0) {
    formValue.value.tableData = val;
  } else {
    formValue.value.tableData = [];
  }
};
// 提交
const handleSubmit = async (formEl: any, isFlag: Boolean) => {
  if (!formEl) return;
  await formEl.validate(async valid => {
    if (valid) {
      if (formValue.value.tableData && formValue.value.tableData.length > 0) {
        const arr = [];
        formValue.value.tableData.forEach(item => {
          arr.push(item.id);
        });
        formValue.value.sparePartIds = arr;
        if (isFlag) {
          formValue.value.isDraft = true;
        } else {
          formValue.value.isDraft = false;
        }
        const params = formValue.value;
        if (props.drawerType === "add") {
          await addSparePartsTakeStock(params);
          PxMessage.success("创建成功");
          emits("backMainPage");
          emits("queryTable");
        } else if (props.drawerType === "edit") {
          await editSparePartsTakeStock(params);
          PxMessage.success("编辑成功");
          emits("backMainPage");
          emits("queryTable");
        }
      } else {
        PxMessage.error("备件列表不能为空");
      }
    }
  });
};
// 删除单条设备
const handleEqpDelete = index => {
  formValue.value.tableData.splice(index, 1);
};

// 外部封装好的组件
// 科室组件调用父组件
const changeClassName = val => {
  formValue.value.className = val;
  formValue.value.tableData = [];
  changeTakeStockScope();
};
</script>
<style lang="scss" scoped>
@import url("@/views/all/equip/scss/add-detail.scss");
.equip-table-pagination {
  width: 100%;
  margin-top: 0;
  :deep(.px-pagination) {
    right: 0;
  }
}
</style>
